import { defineStore } from 'pinia'
import { remove } from 'lodash-es'
import { getJsonData, changeData } from '@/utils/file'
import dayjs from 'dayjs'

export const useBillStore = defineStore('bill', {
    state: () => {
		return {
			list: [],
		}
    },
    actions: {
		getPath(curMonth){
			const currentDate = curMonth ? curMonth : dayjs().format('YYYY-MM') 
			return "_bill/" + currentDate + ".json"
		},
		getList(curMonth){
			getJsonData(this.getPath(curMonth)).then(res=>{
				this.list = res
			}).catch((err)=>{
				this.list =  []
			})
		},
		addItem(item, curMonth){
			this.list.unshift(item)
			changeData(this.getPath(curMonth), 0, this.list)
		},
		deleteItem(id){
			this.list = remove(this.list, (item)=>item.timestamp!==id)
			changeData(this.getPath(dayjs(id).format('YYYY-MM')), 0, this.list)
		},
		editItem(obj){
			const index = this.list.findIndex(item=>item.timestamp===obj.timestamp)
			if(index>-1){
				this.list[index] = obj
				changeData(this.getPath(dayjs(obj.timestamp).format('YYYY-MM')), 0, this.list)
			}
		},
    }
})